package com.hmall.service.impl;

import com.hmall.dto.RequestParams;
import com.hmall.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public List<String> suggestion(String key) {

        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> getfilter(RequestParams requestParams) {

        try {
            SearchRequest request = new SearchRequest("item");
            //query
            buildBasicQuery(requestParams, request);
            //设置size
            request.source().size(0);
            //聚合
            buildAggregation(request);
            //发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //根据品牌名称，获得品牌结果
            List<String> categoryList = getAggByName(aggregations,"categoryAgg");
            result.put("category", categoryList);
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            result.put("brand", brandList);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    private void buildBasicQuery(RequestParams requestParams, SearchRequest request) {
        //构建booleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索
        String key = requestParams.getKey();
        if (key==null||"".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        //品牌条件
        if(requestParams.getBrand()!=null &&!requestParams.getBrand().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("brand",requestParams.getBrand()));
        }
        //分类条件
        if (requestParams.getCategory()!=null&&requestParams.getCategory().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("category",requestParams.getCategory()));
        }
        if (requestParams.getMinPrice()!=null&&requestParams.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(requestParams.getMinPrice()).lte(requestParams.getMaxPrice()));
    }
        request.source().query(boolQuery);
    }
    private void  buildAggregation (SearchRequest request ){
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
        request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(20));
    }
    private List<String> getAggByName(Aggregations aggregations,String aggName){
        //根据聚合名称获得聚合结果
       Terms brandTerms= aggregations.get(aggName);
       //获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //遍历
      List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String string = bucket.getKeyAsString();
            brandList.add(string);
        }return brandList;
    }
}

